import { useRouter } from 'vue-router'
import { useKeepAliveStore } from '@/store/modules/keepAlive'

function handleError(e) {
  console.error(e)
}

/**
 * 页面切换
 * @param { Object } router 可选参数 路由对象，默认为当前路由对象
 * */ 
export function useGo(router) {
  const _router = router || useRouter()

  return function (to, opt) {
    if (!to) return
    const replace = opt?.replace || false
    const keepAlive = opt?.keepAlive || false
    if (keepAlive) {
      // 添加缓存标识
      _router.currentRoute.value.params['_visited_'] = true
    }

    replace ? _router.replace(to).catch(handleError) : _router.push(to).catch(handleError)
  }
}

/**
 * 刷新页面
 * @param { Object } router 可选参数 路由对象，默认为当前路由对象
 * */ 
export function useRedo(router) {
  const { push, currentRoute } = router || useRouter()
  const { fullPath, name, params = {}, query = {} } = currentRoute.value
  const REDIRECT_NAME = 'RedirectPage'
  return function () {
    // 避免死循环
    if (name === REDIRECT_NAME) return

    // 清除页面缓存
    const keepAliveStore = useKeepAliveStore()
    keepAliveStore.delCachePage(name)
    
    let _params = {
      _redirect_path: fullPath,
      _redirect_name: name,
      _redirect_params: JSON.stringify(params),
      _redirect_query: JSON.stringify(query),
    }

    push({ name: REDIRECT_NAME, params: _params })
  }
}
